package mail.gui;

import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.swing.GroupLayout;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.LayoutStyle;

import mail.MultiEmail;
import mail.bean.EmailBean;
import mail.util.FileUtil;
import mail.util.StringUtil;

public class MailPanel extends JPanel {
  private JList attachFileList;
  private JTextField subject;
  private JTextField sender;
  private JTextField receiver;
  private JEditorPane editorPane = null;
  private MultiEmail top = null;
  private EmailBean mail = null;
  
  public JList getAttachFileList() {
    return attachFileList;
  }

  public void setAttachFileList(JList attachFileList) {
    this.attachFileList = attachFileList;
  }

  public JTextField getSubject() {
    return subject;
  }

  public void setSubject(JTextField subject) {
    this.subject = subject;
  }

  public JTextField getSender() {
    return sender;
  }

  public void setSender(JTextField sender) {
    this.sender = sender;
  }

  public JTextField getReceiver() {
    return receiver;
  }

  public void setReceiver(JTextField receiver) {
    this.receiver = receiver;
  }
  
  
  public void showMail(EmailBean mail) {
    this.mail = mail;
    editorPane.setContentType(mail.getContentType());
    editorPane.setText(mail.getContent());
    subject.setText(mail.getSubject());
    sender.setText(mail.getSender());
    receiver.setText("");
    if(mail.getAttach() != null && mail.getAttach().size() > 0) {
      String[] attachFiles = new String[mail.getAttach().size()];
      attachFiles = mail.getAttach().keySet().toArray(attachFiles);
      attachFileList.setListData(attachFiles);
    }else {
      attachFileList.setListData(new String[0]);
    }
    
  }
  
	public MailPanel(MultiEmail multiEmail) {
		super();
		setPreferredSize(new Dimension(580, 340));
		top = multiEmail;

		JScrollPane scrollPane;
		scrollPane = new JScrollPane();
		scrollPane.setPreferredSize(new Dimension(470, 260));

		editorPane = new JEditorPane();
		editorPane.setContentType("text/plain");
		scrollPane.setViewportView(editorPane);

	  JLabel subjectLabel;
	  subjectLabel = new JLabel();
	  subjectLabel.setText("Subject:");

	  JLabel senderLabel;
	  senderLabel = new JLabel();
	  senderLabel.setText("Sender:");

	  JLabel receiverLabel;
	  receiverLabel = new JLabel();
	  receiverLabel.setText("Receiver:");

	  receiver = new JTextField();

	  sender = new JTextField();

	  subject = new JTextField();
	  
	  
	  JScrollPane attachScroll = new JScrollPane();

	  attachFileList = new JList();
	  attachFileList.setVisibleRowCount(2);
	  attachFileList.addMouseListener(new MouseAdapter() {
	    public void mouseClicked(MouseEvent e) {
	      super.mouseClicked(e);
	      if(e.getClickCount() == 2) {
	        boolean result = true;
	        String attachedFile = (String)attachFileList.getSelectedValue();
	        if(attachedFile != null) {
	          JFileChooser jfc = new JFileChooser(new File("."));
	          jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
	          if(jfc.showSaveDialog(top) == JFileChooser.APPROVE_OPTION) {
	            File path = jfc.getSelectedFile();
	            String attachPath = mail.getAttach().get(attachedFile);
	            FileInputStream fis = null;
	            FileOutputStream fos = null;
	            try {
                byte[] tmp = new byte[1024];
                fis = new FileInputStream(attachPath);
                int len;
                if(path.isDirectory()) {
                   fos = new FileOutputStream(path.getAbsoluteFile() + "/" + attachedFile);                   
                }else {
                  if(!FileUtil.createDir(path)) {
                    result = false;
                  }
                  fos = new FileOutputStream(path + "/" + attachedFile);
                }
                while((len = fis.read(tmp)) > -1) {
                  fos.write(tmp, 0, len);
                }
              } catch (FileNotFoundException e1) {
                e1.printStackTrace();
                result = false;
              } catch (IOException e1) {
                e1.printStackTrace();
                result = false;
              } finally {
                if(fis != null ) {
                  try {
                    fis.close();
                  } catch (IOException e1) {
                    e1.printStackTrace();
                  }
                }
                if(fos != null) {
                  try {
                    fos.close();
                  } catch (IOException e1) {
                    e1.printStackTrace();
                  }
                }
                if(!result) {
                  JOptionPane.showMessageDialog(top, "Create file failed!", "Alert", 
                      JOptionPane.ERROR_MESSAGE);
                }
              }
	          }
	        }
	      }
	    }
	  });
	  attachScroll.setViewportView(attachFileList);

	  JLabel attachLabel;
	  attachLabel = new JLabel();
	  attachLabel.setText("Attached Files:");
	  final GroupLayout groupLayout = new GroupLayout((JComponent) this);
	  groupLayout.setHorizontalGroup(
	    groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
  	    .addGroup(groupLayout.createSequentialGroup()
    	    .addContainerGap()
    	    .addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
      	    .addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 556, Short.MAX_VALUE)
      	    .addGroup(groupLayout.createSequentialGroup()
        	    .addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
          	    .addComponent(receiverLabel)
          	    .addComponent(senderLabel)
          	    .addComponent(subjectLabel))
        	    .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
        	    .addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
          	    .addComponent(receiver)
          	    .addComponent(sender)
          	    .addComponent(subject, GroupLayout.DEFAULT_SIZE, 293, Short.MAX_VALUE))
        	    .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
        	    .addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
          	    .addComponent(attachScroll, GroupLayout.PREFERRED_SIZE, 178, GroupLayout.PREFERRED_SIZE)
          	    .addComponent(attachLabel))))
    	    .addContainerGap())
	  );
	  groupLayout.setVerticalGroup(
	    groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
  	    .addGroup(groupLayout.createSequentialGroup()
    	    .addContainerGap()
    	    .addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
      	    .addComponent(subjectLabel)
      	    .addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
        	    .addComponent(subject, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        	    .addComponent(attachLabel)))
    	    .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
    	    .addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
      	    .addGroup(groupLayout.createSequentialGroup()
        	    .addComponent(senderLabel)
        	    .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
        	    .addComponent(receiverLabel))
      	    .addGroup(groupLayout.createSequentialGroup()
        	    .addComponent(sender, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        	    .addGap(4, 4, 4)
        	    .addComponent(receiver, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
      	    .addComponent(attachScroll, GroupLayout.PREFERRED_SIZE, 48, GroupLayout.PREFERRED_SIZE))
    	    .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
    	    .addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 240, GroupLayout.PREFERRED_SIZE)
    	    .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
	  );
	  setLayout(groupLayout);
	}
  public JEditorPane getEditorPane() {
    return editorPane;
  }
  public void setEditorPane(JEditorPane editorPane) {
    this.editorPane = editorPane;
  }

}
